package com.example.java_websocket.config;

import org.mapstruct.Qualifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

@Configuration
public class RedisConfig {

//    @Autowired
//    private MessageListenerAdapter messageListenerAdapter;
    // 聊天室订阅channel号
    public static String CHANNEL = "chat_channel";
    //CHANNEL 是 Redis 的频道名称，用于发布和订阅消息。
    //这里的频道名是 chat_channel，表示这是一个与聊天相关的频道
//    @Autowired
//    private MessageListenerAdapter listenerAdapter;
//    //消息监听配置
//    @Bean
//    public RedisMessageListenerContainer redisContainer(RedisConnectionFactory connectionFactory) {
//        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
//        container.setConnectionFactory(connectionFactory);
//        container.addMessageListener(listenerAdapter,new ChannelTopic("chat_channel"));
//        return container;
//    }
    /**
     * 配置redis序列化方式
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory factory) {

        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        // 使用String序列化Key
        template.setKeySerializer(RedisSerializer.string());
        template.setHashKeySerializer(RedisSerializer.string());

        // 使用JSON序列化Value
        Jackson2JsonRedisSerializer<Object> serializer =
                new Jackson2JsonRedisSerializer<>(Object.class);
        template.setValueSerializer(serializer);
        template.setHashValueSerializer(serializer);

        return template;
    }

    ////////////   redis 发布订阅配置   //////////////////
/**
 * 订阅redis
 *
 * @param connectionFactory redis连接配置工厂
 * @param listener          频道消费者
 * @return RedisMessageListenerContainer
 */

@Bean
    RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory, MessageListener listener){
    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    // 订阅特定频道
    container.setConnectionFactory(connectionFactory);
    // 订阅聊天室频道
    container.addMessageListener(listener,new PatternTopic(CHANNEL));
    return container;
}
}